package com.an.consumer;

import cn.hutool.core.util.RandomUtil;
import com.an.common.constant.Constants;
import com.an.common.core.domain.bo.SendCodeBo;
import com.an.common.enums.CodeTemplateType;
import com.an.common.utils.StringUtils;
import com.an.common.utils.email.MailUtils;
import com.an.common.utils.redis.RedisUtils;
import com.an.common.constant.MqConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * mq消费者
 *
 * @author: Ann
 * @createDate: 2024/04/09
 */
@Component
@Slf4j
public class MqSmsConsumer {

    /**
     * 处理测试发送消息
     *
     * @param message 消息
     * @return
     * @author: Ann
     * @createDate: 2024/04/09
     */
    @RabbitListener(bindings = @QueueBinding(
        value = @Queue(value = MqConstants.TEST_SEND_QUEUE, durable = "true"),
        exchange = @Exchange(value = MqConstants.TEST_EXCHANGE, type = "topic"),
        key = {MqConstants.TEST_SEND_KEY}
    ))
    public void handleTestSendMessage(String message) {
        System.out.println("Mq消费消息：" + message);
    }


    /**
     * 处理发送邮件消息
     *
     * @param sendCodeBo 发送代码bo
     * @return
     * @author: Ann
     * @createDate: 2024/04/09
     */
    @RabbitListener(bindings = @QueueBinding(
        value = @Queue(value = MqConstants.MAIL_SEND_QUEUE, durable = "true"),
        exchange = @Exchange(value = MqConstants.MAIL_EXCHANGE, type = "topic"),
        key = {MqConstants.MAIL_SEND_KEY}
    ))
    public void handleSendMailMessage(SendCodeBo sendCodeBo) {
        String email = sendCodeBo.getEmail();
        String type = sendCodeBo.getType();
        CodeTemplateType codeTemplateType = CodeTemplateType.findTemplate(type);
        assert codeTemplateType != null;
        //接口已过滤非法值
        String subject = codeTemplateType.getSubject();
        String content = codeTemplateType.getContent();
        //生成验证码
        String code = RandomUtil.randomNumbers(6);
        //发送验证码
        String template = StringUtils.format(content, code);
        String messageId = MailUtils.sendText(email, subject, template);
        if (StringUtils.isNotBlank(messageId)) {
            //存储redis
            RedisUtils.setCacheObject(codeTemplateType.getKeyPrefix() + email, code,
                Duration.ofMinutes(Constants.MAIL_CODE_EXPIRATION));
        }

    }


}
